package org.example.fortest.service.impl;

import org.example.fortest.model.User;
import org.example.fortest.repository.UserRepository;
import org.example.fortest.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public List<User> selectUserList(User user, Pageable pageable) {
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("username", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<User> example = Example.of(user, matcher);
        Page<User> users = userRepository.findAll(example, pageable);
        return users.getContent();

    }

    @Override
    public boolean checkUserNameUnique(User user) {
        User usercheck=new User();
        usercheck.setUsername(user.getUsername());
        Example<User> example = Example.of(usercheck);
        List<User> users=userRepository.findAll(example);
        if (users.size()>0) {
            User currentUser=users.get(0);
            if (currentUser.getId().equals(user.getId())) {
                return false;
            }
            return true;
        }
        return false;
    }

    @Override
    public boolean insertUser(User user) {
        userRepository.save(user);
        return user.getId() != null;
    }

    @Override
    public boolean updataUser(User user) {
        Long id=user.getId();
        Optional<User> userOptional=userRepository.findById(id);
        if (!userOptional.isPresent()) {
            return false;
        }
        User oldUser=userOptional.get();
        BeanUtils.copyProperties(user,oldUser);

        userRepository.save(oldUser);
        return null != oldUser.getId();
    }

    @Override
    @Transactional
    public boolean deleteByFlag(Long id) {
//        userRepository.deleteByFlag(id);
        userRepository.deleteById(id);
        return true;
    }
}
